package com.pokemon.server;

import com.pokemon.services.PokemonService;
import com.pokemon.services.TrainerService;
import javax.annotation.Resource;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

/**
 *
 * @author Ladislav
 */
public class Server {
    
//    @Resource(name = "authenticationManager")
//    private static AuthenticationManager authenticationManager;
    
    public static void main( String[] args ) {
        ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-context.xml");
        AuthenticationManager authenticationManager = (AuthenticationManager) ctx.getBean("authenticationManager");
        
        try {
            Authentication authenticate = authenticationManager.authenticate(new UsernamePasswordAuthenticationToken("soap", "soap"));
            if (authenticate.isAuthenticated()) {
                SecurityContextHolder.getContext().setAuthentication(authenticate);             
                System.out.println("Authenticated ... ");
                //System.out.println(SecurityContextHolder.getContext().getAuthentication().getPrincipal());
                //System.out.println(SecurityContextHolder.getContext().getAuthentication().getCredentials());
            }
        }
        catch (AuthenticationException e) { 
            System.out.println("Not Authenticated ... ");
        }
        
        TrainerService trainerService = (TrainerService)ctx.getBean("trainerService");
        PokemonService pokemonService = (PokemonService)ctx.getBean("pokemonService");
        
        TrainerServiceImpl trainerSer = new TrainerServiceImpl();
        PokemonServiceImpl pokemonSer = new PokemonServiceImpl();

        trainerSer.setService(trainerService);
        pokemonSer.setService(pokemonService);

        ServiceServer server = new ServiceServer(trainerSer,pokemonSer);
        server.run();
       
        System.out.println("Server ready ... ");


    }   
}
